package com.wanxi.servlet.user;

import com.alibaba.fastjson2.JSONObject;
import com.wanxi.dto.ResultDTO;
import com.wanxi.service.UserService;
import com.wanxi.service.impl.UserServiceImpl;
import com.wanxi.vo.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        2.得到数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
//        req.getServletContext();
        String vCode = (String) req.getSession().getAttribute("vCode");
//        3.封装到model
        UserVO userVO = UserVO.builder()
                .username(username)
                .password(password)
                .code(code)
                .vCode(vCode)
                .build();
//        4.调用逻辑层
        UserService userService = new UserServiceImpl();
        ResultDTO resultDTO = userService.login(userVO);
        if (resultDTO.getMsg().equals("success")) {
            req.getSession().setAttribute("username", username);
        }
//        5.响应给前端
        resp.getWriter().println(JSONObject.toJSONString(resultDTO));
    }
}
